package com.zsxb.crm.exception;

import com.zsxb.crm.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

//@ControllerAdvice
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(BaseException.class)
    @ResponseBody
    public Result error(BaseException e){
        e.printStackTrace();
        return Result.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result error(Exception e){
        e.printStackTrace();
        return Result.error(e.getMessage());
    }



    /**
     * 重复添加异常
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result<?> repeatAddition(SQLIntegrityConstraintViolationException ex){
        if(ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            String msg = split[2].replace("'", "") + "已存在";
            log.error(msg);
            return Result.error(msg);
        }
        return Result.error("未知错误");
    }


}
